'
' Will Strohl (wills@strohlsitedesign.com)
' http://www.willstrohl.com
'
'Copyright (c) 2009, Will Strohl
'All rights reserved.
'
'Redistribution and use in source and binary forms, with or without modification, are 
'permitted provided that the following conditions are met:
'
'Redistributions of source code must retain the above copyright notice, this list of 
'conditions and the following disclaimer.
'
'Redistributions in binary form must reproduce the above copyright notice, this list 
'of conditions and the following disclaimer in the documentation and/or other 
'materials provided with the distribution.
'
'Neither the name of StrohlSiteDesign.com nor the names of its contributors may be 
'used to endorse or promote products derived from this software without specific prior 
'written permission.
'
'THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
'EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
'OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
'SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
'INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
'TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR 
'BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
'CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
'ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH 
'DAMAGE.
'

Imports DotNetNuke
Imports DotNetNuke.Entities.Modules
Imports DotNetNuke.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Collections.Generic
Imports System.Reflection
Imports System.Text.RegularExpressions

Imports WillStrohl.Modules.FeedHandler.FeedHandlerController

Namespace WillStrohl.Modules.FeedHandler

    ''' <summary>
    ''' This is the view control for the FeedHandler module.
    ''' </summary>
    ''' <remarks>
    ''' </remarks>
    ''' <history>
    ''' </history>
    Partial Class EditFeed
        Inherits WNSPortalModuleBase

#Region " Private Members "

        Private Const c_HostItemFormat As String = "{0} :: {1} :: {2}"
        Private Const c_EditItemFormat As String = "{0} :: {1}"
        Private Const c_AnchorTag As String = "<a href=""{0}"" target=""_blank"">{0}</a>"

#End Region

#Region " Private Properties "

        ''' <summary>
        ''' FeedId - this is the id of the feed, found in the querystring
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        ''' <history>
        ''' </history>
        Private ReadOnly Property FeedId() As Integer
            Get
                If Not Request.Params("FeedId") Is Nothing Then
                    Return Integer.Parse(Request.Params("FeedId").ToString, Globalization.NumberStyles.Integer)
                Else
                    Return Null.NullInteger
                End If
            End Get
        End Property

#End Region

#Region " Event Handlers "

        ''' <summary>
        ''' Page_Load runs when the control is loaded
        ''' </summary>
        ''' <remarks>
        ''' </remarks>
        ''' <history>
        ''' </history>
        Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Try
                If Not Page.IsPostBack Then
                    Me.BindData()
                End If
            Catch exc As Exception ' Module failed to load
                ProcessModuleLoadException(Me, exc)
            End Try
        End Sub

        Private Sub ddlRssModule_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlRssModule.SelectedIndexChanged
            If Me.ddlRssModule.SelectedIndex = 0 Then
                Me.divModuleFeedUrl.InnerHtml = String.Empty
            Else
                ' the selected value of the drop down list should be in the following format:
                ' [ModuleId]::[TabId]::[PortalId]
                Dim strParam() As String = Me.ddlRssModule.SelectedValue.Split(CChar(ARRAY_DELIMITER))
                Me.BindModuleRssUrl(Integer.Parse(strParam(0), Globalization.NumberStyles.Integer), Integer.Parse(strParam(1), Globalization.NumberStyles.Integer))
            End If
        End Sub

        Private Sub lnkCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkCancel.Click
            Response.Redirect(NavigateURL())
        End Sub

        Private Sub lnkDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkDelete.Click
            If FeedId <> Null.NullInteger Then
                FeedHandlerController.DeleteFeed(Me.FeedId)
                Response.Redirect(NavigateURL())
            Else
                DotNetNuke.UI.Skins.Skin.AddModuleMessage(Me, _
                    Me.GetLocalizedString("Error.FeedIdNull"), _
                    Skins.Controls.ModuleMessage.ModuleMessageType.RedError)
            End If
        End Sub

        ''' <summary>
        ''' lnkSubmit_Click - Initiates the saving of the feed values
        ''' </summary>
        ''' <param name="sender"></param>
        ''' <param name="e"></param>
        ''' <remarks></remarks>
        ''' <history>
        ''' [wstrohl] - 2009024 - Added logic for the new ImportFeedUrl setting
        ''' </history>
        Private Sub lnkSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkSubmit.Click
            If Page.IsValid Then
                Try
                    Dim intModuleId As Integer = Null.NullInteger
                    Dim intTabId As Integer = Null.NullInteger
                    Dim intPortalId As Integer = Null.NullInteger
                    Dim strFeedHandlerUrl As String = Null.NullString

                    If Me.radFeedType.SelectedIndex = 1 Then
                        intModuleId = Me.ModuleId
                        intTabId = Me.TabId
                        intPortalId = Me.PortalId
                    ElseIf Me.radFeedType.SelectedIndex = 0 Then
                        Me.txtFeedImportUrl.Text = Null.NullString
                        ' the selected value of the drop down list should be in the following format:
                        ' [ModuleId]::[TabId]::[PortalId]
                        Dim strParam() As String = Me.ddlRssModule.SelectedValue.Split(CChar(ARRAY_DELIMITER))
                        intModuleId = Integer.Parse(strParam(0), Globalization.NumberStyles.Integer)
                        intTabId = Integer.Parse(strParam(1), Globalization.NumberStyles.Integer)
                        intPortalId = Integer.Parse(strParam(2), Globalization.NumberStyles.Integer)
                    End If

                    Dim ctlModule As New Entities.Modules.ModuleController
                    Dim mInfo As New Entities.Modules.ModuleInfo
                    mInfo = ctlModule.GetModule(intModuleId, intTabId, False)

                    Dim ctlTab As New Entities.Tabs.TabController
                    Dim tInfo As New Entities.Tabs.TabInfo
                    tInfo = ctlTab.GetTab(mInfo.TabID, mInfo.TabID, False)

                    Dim pInfo As New Entities.Portals.PortalInfo
                    pInfo = FeedHandlerController.GetPortalInfo(mInfo.PortalID)

                    Dim pAlias As New Entities.Portals.PortalAliasInfo
                    Dim ctlAlias As New Entities.Portals.PortalAliasController
                    pAlias = CType(ctlAlias.GetPortalAliasArrayByPortalID(mInfo.PortalID)(0), Entities.Portals.PortalAliasInfo)
                    Dim stgs As New Entities.Portals.PortalSettings(mInfo.TabID, pAlias)

                    If Me.FeedId <> Null.NullInteger Then
                        ' update the current record
                        If String.IsNullOrEmpty(Me.txtFeedImportUrl.Text) Then
                            FeedHandlerController.UpdateFeed(Me.FeedId, Me.txtFeedName.Text.Trim, Me.ModuleId, intModuleId, _
                                String.Empty, _
                                FeedHandlerController.GetFeedHandlerUrl(Me.FeedId, mInfo.ModuleID, Me.ModuleConfiguration.FolderName, stgs.PortalAlias.HTTPAlias))
                        Else
                            FeedHandlerController.UpdateFeed(Me.FeedId, Me.txtFeedName.Text.Trim, Me.ModuleId, Null.NullInteger, _
                                Me.txtFeedImportUrl.Text, _
                                FeedHandlerController.GetFeedHandlerUrl(Me.FeedId, mInfo.ModuleID, Me.ModuleConfiguration.FolderName, stgs.PortalAlias.HTTPAlias))
                        End If
                    Else
                        ' add a new record

                        Dim intFeed As Integer = FeedHandlerController.AddFeed(Me.txtFeedName.Text.Trim, Me.ModuleId, intModuleId, Me.txtFeedImportUrl.Text, String.Empty)
                        If intFeed > Null.NullInteger Then
                            If String.IsNullOrEmpty(Me.txtFeedImportUrl.Text) Then
                                FeedHandlerController.UpdateFeed(intFeed, Me.txtFeedName.Text.Trim, Me.ModuleId, intModuleId, _
                                    String.Empty, _
                                    FeedHandlerController.GetFeedHandlerUrl(intFeed, mInfo.ModuleID, Me.ModuleConfiguration.FolderName, stgs.PortalAlias.HTTPAlias))
                            Else
                                FeedHandlerController.UpdateFeed(intFeed, Me.txtFeedName.Text.Trim, Me.ModuleId, Null.NullInteger, _
                                    Me.txtFeedImportUrl.Text, _
                                    FeedHandlerController.GetFeedHandlerUrl(intFeed, mInfo.ModuleID, Me.ModuleConfiguration.FolderName, stgs.PortalAlias.HTTPAlias))
                            End If
                        End If
                    End If

                    Response.Redirect(NavigateURL)
                Catch ex As Exception
                    DotNetNuke.Services.Exceptions.LogException(ex)
                    ProcessModuleLoadException(Me.GetLocalizedString("Error.SaveFeed"), Me, ex, True)
                End Try
            End If
        End Sub

        ''' <summary>
        ''' radFeedType_SelectedIndexChanged - initiates and changes the view for the different XML feed sources
        ''' </summary>
        ''' <param name="sender"></param>
        ''' <param name="e"></param>
        ''' <remarks></remarks>
        ''' <history>
        ''' [wstrohl] - 20090324 - Created
        ''' </history>
        Private Sub radFeedType_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles radFeedType.SelectedIndexChanged
            Me.ToggleFeedSource()
        End Sub

#End Region

#Region " Private Methods "

        ''' <summary>
        ''' BindData - this method initializes the binding of all controls
        ''' </summary>
        ''' <remarks></remarks>
        ''' <history>
        ''' [wstrohl] - 20090324 - Added the necessary binding for the new import url setting
        ''' </history>
        Private Sub BindData()
            Me.LocalizePage()
            Me.BindModulesToList()

            Me.lnkDelete.Visible = (Me.FeedId <> Null.NullInteger)

            If Me.radFeedType.Items.Count = 0 Then
                Me.radFeedType.Items.Add(New ListItem(Me.GetLocalizedString("radFeedType.Item.01")))
                Me.radFeedType.Items.Add(New ListItem(Me.GetLocalizedString("radFeedType.Item.02")))
                Me.radFeedType.SelectedIndex = 0
                Me.ToggleFeedSource()
            End If

            If Me.FeedId <> Null.NullInteger Then
                Dim objFeed As New FeedInfo
                objFeed = FeedHandlerController.GetFeed(Me.FeedId)

                If Not objFeed Is Nothing Then

                    Me.txtFeedName.Text = objFeed.FeedName

                    If objFeed.FeedModuleId > Null.NullInteger Then
                        Me.radFeedType.SelectedIndex = 0

                        Dim info As New ModuleIdInfo
                        info = FeedHandlerController.GetModuleIds(objFeed.FeedModuleId)

                        Dim strValue As String = GetModuleListItemValue(info)
                        For Each itm As ListItem In Me.ddlRssModule.Items
                            itm.Selected = String.Equals(itm.Value, strValue, StringComparison.InvariantCultureIgnoreCase)
                        Next

                        Me.BindModuleRssUrl(info.ModuleId, info.TabId)
                        Me.BindHandlerRssUrl(objFeed, info)
                    Else
                        Me.radFeedType.SelectedIndex = 1

                        Me.txtFeedImportUrl.Text = objFeed.FeedImportUrl
                        Me.divModuleFeedUrl.Controls.Add(New LiteralControl(String.Format(c_AnchorTag, objFeed.FeedImportUrl)))
                        Dim mInfo As New ModuleIdInfo
                        mInfo.ModuleId = Me.ModuleId
                        mInfo.PortalId = Me.PortalId
                        mInfo.TabId = Me.TabId
                        Me.BindHandlerRssUrl(objFeed, mInfo)
                    End If

                    Me.ToggleFeedSource()

                Else
                    DotNetNuke.UI.Skins.Skin.AddModuleMessage(Me, Me.GetLocalizedString("Error.FeedNotFound"), _
                        Skins.Controls.ModuleMessage.ModuleMessageType.RedError)
                End If
            End If
        End Sub

        ''' <summary>
        ''' BindModulesToList - this method binds the module information to the dropdownlist
        ''' </summary>
        ''' <remarks></remarks>
        ''' <history>
        ''' </history>
        Private Sub BindModulesToList()
            If Me.ddlRssModule.Items.Count = 0 Then
                Me.ddlRssModule.Items.Add(New ListItem("---"))

                Dim tInfo As New Entities.Tabs.TabInfo
                Dim ctlTab As New Entities.Tabs.TabController
                Dim collModule As New List(Of ModuleInfo)
                collModule = FeedHandlerController.GetRSSEnabledModules

                For Each mInfo As ModuleInfo In collModule
                    tInfo = ctlTab.GetTab(mInfo.TabID, mInfo.PortalID, False)
                    If UserInfo.IsSuperUser Then
                        Me.ddlRssModule.Items.Add(New ListItem(String.Format(c_HostItemFormat, mInfo.PortalID.ToString, tInfo.TabName, mInfo.ModuleTitle), String.Concat(mInfo.ModuleID.ToString, ARRAY_DELIMITER, mInfo.TabID.ToString, ARRAY_DELIMITER, mInfo.PortalID)))
                    Else
                        Me.ddlRssModule.Items.Add(New ListItem(String.Format(c_EditItemFormat, tInfo.TabName, mInfo.ModuleTitle), String.Concat(mInfo.ModuleID.ToString, ARRAY_DELIMITER, mInfo.TabID.ToString, ARRAY_DELIMITER, mInfo.PortalID)))
                    End If
                Next
            End If
        End Sub

        ''' <summary>
        ''' LocalizePage - this method centralizes the localization of all of the controls
        ''' </summary>
        ''' <remarks></remarks>
        ''' <history>
        ''' </history>
        Private Sub LocalizePage()
            Me.lnkCancel.Text = Me.GetLocalizedString("lnkCancel.Text")
            Me.lnkDelete.Text = Me.GetLocalizedString("lnkDelete.Text")
            Me.lnkDelete.Attributes.Add("onclick", String.Format("return confirm('{0}');", Me.GetLocalizedString("lnkDelete.Confirm")))
            Me.lnkSubmit.Text = Me.GetLocalizedString("lnkSubmit.Text")

            Me.rfvFeedName.ErrorMessage = Me.GetLocalizedString("rfvFeedName.ErrorMessage")
            Me.cvFeedType.ErrorMessage = Me.GetLocalizedString("cvFeedType.ErrorMessage")

            If Me.FeedId = Null.NullInteger Then
                Me.divRssFeedUrl.InnerHtml = Me.GetLocalizedString("divRssFeedUrl.NewItem")
            End If
        End Sub

        ''' <summary>
        ''' BindModuleRssUrl - adds the RSS URL to the UI
        ''' </summary>
        ''' <param name="idModule"></param>
        ''' <param name="idTab"></param>
        ''' <remarks></remarks>
        ''' <history>
        ''' </history>
        Private Sub BindModuleRssUrl(ByVal idModule As Integer, ByVal idTab As Integer)
            Dim ctlModule As New DotNetNuke.Entities.Modules.ModuleController
            Dim mInfo As New DotNetNuke.Entities.Modules.ModuleInfo
            mInfo = ctlModule.GetModule(idModule, idTab, False)

            Dim strLink As String = FeedHandlerController.GetDNNRssUrl(mInfo)
            Me.divModuleFeedUrl.Controls.Add(New LiteralControl(String.Format(c_AnchorTag, strLink)))
        End Sub

        ''' <summary>
        ''' BindHandlerRssUrl - adds the feed handler RSS URL to the UI
        ''' </summary>
        ''' <param name="fInfo"></param>
        ''' <param name="miInfo"></param>
        ''' <remarks></remarks>
        ''' <history>
        ''' </history>
        Private Sub BindHandlerRssUrl(ByVal fInfo As FeedInfo, ByVal miInfo As ModuleIdInfo)
            Dim ctlModule As New DotNetNuke.Entities.Modules.ModuleController
            Dim mInfo As New DotNetNuke.Entities.Modules.ModuleInfo
            mInfo = ctlModule.GetModule(miInfo.ModuleId, miInfo.TabId, False)

            Dim pAlias As New Entities.Portals.PortalAliasInfo
            Dim ctlAlias As New Entities.Portals.PortalAliasController
            pAlias = CType(ctlAlias.GetPortalAliasArrayByPortalID(mInfo.PortalID)(0), Entities.Portals.PortalAliasInfo)
            Dim stgs As New Entities.Portals.PortalSettings(mInfo.TabID, pAlias)

            Dim strLink As String = FeedHandlerController.GetDNNRssUrl(mInfo)
            Me.divRssFeedUrl.Controls.Add(New LiteralControl(String.Format(c_AnchorTag, _
                FeedHandlerController.GetFeedHandlerUrl(fInfo.FeedId, fInfo.ModuleId, Me.ModuleConfiguration.FolderName, stgs.PortalAlias.HTTPAlias) _
            )))
        End Sub

        ''' <summary>
        ''' GetModuleListItemValue - this method returns the parseable listitem value
        ''' </summary>
        ''' <param name="info"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        ''' <history>
        ''' </history>
        Private Function GetModuleListItemValue(ByVal info As ModuleIdInfo) As String
            If Not info Is Nothing Then
                Return String.Concat(info.ModuleId, ARRAY_DELIMITER, info.TabId, ARRAY_DELIMITER, info.PortalId)
            Else
                Return String.Empty
            End If
        End Function

        ''' <summary>
        ''' ToggleFeedSource - this method toggles the view of the module feed source, and the textbox
        ''' </summary>
        ''' <remarks></remarks>
        ''' <history>
        ''' [wstrohl] - 20090324 - Created
        ''' </history>
        Private Sub ToggleFeedSource()
            Me.divFeedImportUrl.Visible = (Me.radFeedType.SelectedIndex = 1)
            Me.divRssModule.Visible = Not (Me.radFeedType.SelectedIndex = 1)
        End Sub

        ''' <summary>
        ''' cvFeedType_ServerValidate - validates the feed source
        ''' </summary>
        ''' <param name="source"></param>
        ''' <param name="args"></param>
        ''' <remarks></remarks>
        ''' <history>
        ''' [wstrohl] - 20090324 - Created
        ''' </history>
        Private Sub cvFeedType_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles cvFeedType.ServerValidate
            If Me.radFeedType.SelectedIndex = 0 Then
                args.IsValid = (Me.ddlRssModule.SelectedIndex > 0)
                Exit Sub
            Else
                args.IsValid = Not String.IsNullOrEmpty(Me.txtFeedImportUrl.Text)
                Exit Sub
            End If
        End Sub

#End Region

    End Class

End Namespace
